package com.xxxy;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Conntest {
    // 加载 c3p0 配置（默认读取类路径下的 c3p0-config.xml）
    private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 1. 从连接池获取连接
            conn = dataSource.getConnection();

            // 2. 测试查询（示例：查询数据库版本）
            String sql = "SELECT VERSION() AS db_version";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            // 3. 输出结果
            if (rs.next()) {
                System.out.println("数据库连接成功！");
                System.out.println("数据库版本: " + rs.getString("db_version"));
            }

        } catch (SQLException e) {
            System.err.println("数据库连接失败！错误信息：");
            e.printStackTrace();
        } finally {
            // 4. 释放资源（连接会返回连接池）
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}